<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>getSnapshotBeforeUpdate应用场景</title>
		<style>
			.list{
				background-color: skyblue;
				padding: 0px;
				list-style: none;
				overflow: auto;
				width: 300px;
				height: 150px;
			}
			.news{
				background-color: orange;
				width: 100%;
				height: 30px;
			}
		</style>
		<!-- 引入react核心库 -->
		<script type="text/javascript" src="../js/react.js"></script>
		<!-- 引入react-dom，用于支持react操作DOM -->
		<script type="text/javascript" src="../js/react-dom.js"></script>
		<!-- 引入babel，用于解析jsx为js -->
		<script type="text/javascript" src="../js/babel.min.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器 -->
		<div id="root"></div>

		<script type="text/babel">
			//定义一个组件
			class Demo extends React.Component{
				state = {
					newsList:[]
				}
				componentDidMount(){
					setInterval(()=>{
						//获取原来的新闻列表
						const {newsList} = this.state
						//创建一个新闻
						const n = '新闻' + newsList.length
						//更新state
						this.setState({newsList:[n,...newsList]})
					},1000)
				}
				render(){
					console.log('---render---')
					return (
						<ul className="list" ref="list">
							{
								this.state.newsList.map((news,index)=>{
									return <li className="news" key={index}>{news}</li>
								})
							}	
						</ul>
					)
				}
				getSnapshotBeforeUpdate(){
					//此时还没有更新页面的DOM，获取一下当前内容区的高度
					return this.refs.list.scrollHeight
				}
				componentDidUpdate(_,__,snapValue){
					if(this.refs.list.scrollTop <= 30) return
					this.refs.list.scrollTop += this.refs.list.scrollHeight - snapValue
				}
			}
			ReactDOM.render(<Demo/>,document.getElementById('root'))
		</script>
	</body>
</html>